<template>
  <div class="form-field-config">
    <je-panel v-bind="formFieldOptions" ref="formPanel" force-render>
      <template #top>
        <div class="top">
          <je-button type="text">
            <je-dropdown>
              <a class="txt" @click.prevent
                ><i class="fal fa-plus-circle"></i> 添加 <i class="fal fa-angle-down"></i>
              </a>
              <template #overlay>
                <je-menu @click="handleChangeMenuItem">
                  <je-menu-item key="fieldset" text="分组框">分组框</je-menu-item>
                  <!-- <je-menu-item key="fieldset" text="字段域">分组框(字段域)</je-menu-item> -->
                  <je-menu-item key="displayfield" text="虚拟字段">虚拟字段</je-menu-item>
                  <je-menu-item key="childfuncfield" text="子功能集合">子功能集合</je-menu-item>
                </je-menu>
              </template>
            </je-dropdown>
          </je-button>

          <je-button type="text" @click="handleSave"> <i class="fal fa-save"></i> 保存 </je-button>
          <je-button type="text" @click="handleDelete">
            <i class="fal fa-times"></i> 删除
          </je-button>

          <je-button type="text" @click="handleSort">
            <i class="fal fal fa-sort-alpha-down"></i> 排序整理
          </je-button>

          <je-button type="text" @click="handleJs(false)">
            <i
              class="fas fa-bolt"
              :style="`color:${
                changeJsListener(funcStore.funcBean.FUNCINFO_FORMJSLISTENER) ? '#F4CE4A' : '#8d98ab'
              }`"
            ></i>
            表单JS事件</je-button
          >
          <je-button type="text" @click="handleSync">
            <i class="fal fal fa-copy"></i> 与列表同步
          </je-button>
          <je-button v-if="originType == 'app'" type="text" @click="appPreview">
            <i class="fal fal fa-copy"></i> 移动端效果预览
          </je-button>
          <div class="searchWrap">
            <je-input-search
              v-model:value.trim="searchValue"
              class="search"
              placeholder="搜索"
              allow-clear
              enter-button="搜索"
              style="width: 280px"
              @search="getData('search')"
            >
              <template #prefix> <i class="fal fa-search" /> </template>
            </je-input-search>
          </div>
        </div>
      </template>
      <template #default>
        <div class="tableWrap">
          <je-table
            ref="xTable"
            class="table"
            border
            stripe
            auto-resize
            sync-resize
            draggable
            show-overflow="ellipsis"
            keep-source
            show-header-overflow
            resizable
            header-align="center"
            height="100%"
            :row-class-name="rowClassName"
            :cell-class-name="cellClassName"
            :edit-config="{
              trigger: 'click',
              mode: 'cell',
              showStatus: true,
              showUpdateStatus: true,
            }"
            :field-config="filedsArr"
            :row-config="{ isCurrent: true, isHover: true }"
            :loading="loading"
            :store="tableData"
            size="mini"
            id-property="JE_CORE_RESOURCEFIELD_ID"
            @checkbox-change="selectionChange"
            @checkbox-all="selectionChange"
            @drop="formFieldItemDrop"
            @current-change="onClickRow"
          >
            <!-- <je-table-column type="drag" fixed="left" /> -->
            <je-table-column
              type="checkbox"
              width="40"
              align="center"
              fixed="left"
            ></je-table-column>
            <je-table-column
              field="SY_ORDERINDEX"
              title="序号"
              width="60"
              align="center"
              fixed="left"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                {{ row.SY_ORDERINDEX }}
              </template>
            </je-table-column>
            <je-table-column field="RESOURCEFIELD_CODE" title="编码" min-width="220" fixed="left">
              <template #default="{ row }">
                <div
                  class="eventWrap"
                  @dblclick="showEditFieldConfig(row, 'right')"
                  v-html="formatHightText(searchValue, row.RESOURCEFIELD_CODE)"
                />
              </template>
            </je-table-column>
            <je-table-column
              field="RESOURCEFIELD_NAME"
              title="名称"
              min-width="140"
              fixed="left"
              :edit-render="{ autofocus: '.ant-input' }"
            >
              <template #default="{ row }">
                <span v-html="formatHightText(searchValue, row.RESOURCEFIELD_NAME)"></span>
              </template>
              <template #edit="{ row }">
                <je-input v-model:value="row.RESOURCEFIELD_NAME" />
              </template>
            </je-table-column>
            <je-table-column
              field="RESOURCEFIELD_XTYPE"
              title="类型"
              width="140"
              align="center"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <je-select
                  v-model:value="row.RESOURCEFIELD_XTYPE"
                  allow-clear
                  config-info="JE_FUNC_FIELD_XTYPE,formState.RESOURCEFIELD_XTYPE,code,S"
                >
                </je-select>
              </template>
              <template #default="{ row }">{{
                getSelectCodeToLabel('JE_FUNC_FIELD_XTYPE', row.RESOURCEFIELD_XTYPE)
              }}</template>
            </je-table-column>
            <je-table-column
              v-if="originType == 'app'"
              field="RESOURCEFIELD_USE_SCOPE"
              title="适用范围"
              align="center"
              width="120"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <je-select v-model:value="row.RESOURCEFIELD_USE_SCOPE">
                  <!-- config-info="JE_META_USE_SCOPE,RESOURCEFIELD_USE_SCOPE,code,S" -->
                  <je-select-option
                    v-for="(item, index) in getScopedList"
                    :key="index"
                    :value="item.code"
                    :style="`color: ${item.textColor}`"
                  >
                    {{ item.text }}</je-select-option
                  >
                </je-select>
              </template>
              <template #default="{ row }">
                <div
                  :style="`color: ${getColor('JE_META_USE_SCOPE', row.RESOURCEFIELD_USE_SCOPE)}`"
                >
                  {{ getSelectCodeToLabel('JE_META_USE_SCOPE', row.RESOURCEFIELD_USE_SCOPE) }}</div
                >
              </template>
            </je-table-column>
            <je-table-column
              v-if="originType == 'app'"
              title="移动端标签位置"
              width="140"
              align="center"
              field="RESOURCEFIELD_APP_LABELALIGN"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <je-select
                  v-model:value="row.RESOURCEFIELD_APP_LABELALIGN"
                  allow-clear
                  config-info="JE_FUNC_FIELD_ALIGN,row.RESOURCEFIELD_APP_LABELALIGN,code,S"
                >
                </je-select>
              </template>
              <template #default="{ row }">
                {{
                  getSelectCodeToLabel('JE_FUNC_FIELD_ALIGN', row.RESOURCEFIELD_APP_LABELALIGN)
                }}</template
              >
            </je-table-column>
            <je-table-column
              field="RESOURCEFIELD_HIDDEN"
              title="隐藏"
              width="100"
              align="center"
              type="switch"
            />
            <je-table-column
              field="RESOURCEFIELD_READONLY"
              title="只读"
              width="100"
              align="center"
              type="switch"
            />
            <je-table-column
              title="事件"
              width="60"
              align="center"
              field="RESOURCEFIELD_JSLISTENER"
            >
              <template #default="{ row }">
                <je-tooltip placement="top" title="编辑">
                  <div class="iconWrap" @click="handleJs(row)"
                    ><i
                      class="fas fa-bolt"
                      :style="`color:${
                        changeJsListener(row.RESOURCEFIELD_JSLISTENER) ? '#F4CE4A' : '#8d98ab'
                      }`"
                    ></i
                  ></div>
                </je-tooltip>
              </template>
            </je-table-column>
            <je-table-column
              v-if="!origin"
              field="RESOURCEFIELD_GROUPNAME"
              title="所属组"
              width="140"
              :edit-render="{}"
              align="center"
            >
              <template #edit="{ row }">
                <je-select
                  v-model:value="row.RESOURCEFIELD_GROUPNAME"
                  allow-clear
                  :options="funcStore.groupFields"
                />
              </template>
              <template #default="{ row }">{{
                getSelectLabel(row.RESOURCEFIELD_GROUPNAME, funcStore.groupFields)
              }}</template>
            </je-table-column>
            <je-table-column
              field="RESOURCEFIELD_VALUE"
              title="默认值"
              width="220"
              align="center"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <je-select
                  v-model:value="row.RESOURCEFIELD_VALUE"
                  allow-clear
                  config-info="JE_DEFAULEVALUE,row.RESOURCEFIELD_VALUE,code,S"
                  :editable="true"
                >
                </je-select>
              </template>
              <template #default="{ row }">{{
                getSelectCodeToLabel('JE_DEFAULEVALUE', row.RESOURCEFIELD_VALUE)
              }}</template>
            </je-table-column>
            <je-table-column
              field="RESOURCEFIELD_REQUIRE"
              title="必填"
              width="100"
              align="center"
              type="switch"
            />

            <!-- <je-table-column
              field="RESOURCEFIELD_HISTORY"
              title="历史留痕"
              width="100"
              align="center"
              type="switch"
            /> -->

            <!-- <je-table-column
              field="RESOURCEFIELD_EDITABLE"
              title="可选可编辑"
              width="140"
              align="center"
            >
              <template #default="{ row }">
                <je-checkbox v-model:checked="row.RESOURCEFIELD_EDITABLE" />
              </template>
            </je-table-column> -->

            <je-table-column
              v-if="!originType"
              title="PC端标签位置"
              width="140"
              align="center"
              field="RESOURCEFIELD_LABELALIGN"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <je-select
                  v-model:value="row.RESOURCEFIELD_LABELALIGN"
                  allow-clear
                  config-info="JE_FUNC_FIELD_ALIGN,row.RESOURCEFIELD_LABELALIGN,code,S"
                >
                </je-select>
              </template>
              <template #default="{ row }">{{
                getSelectCodeToLabel('JE_FUNC_FIELD_ALIGN', row.RESOURCEFIELD_LABELALIGN)
              }}</template>
            </je-table-column>

            <je-table-column
              v-if="!origin"
              field="RESOURCEFIELD_ROWFIELD"
              title="依附字段"
              min-width="220"
              :edit-render="{ autofocus: '.ant-input' }"
            >
              <template #edit="{ row }">
                <je-select
                  v-model:value="row.RESOURCEFIELD_ROWFIELD"
                  :options="funcStore.attachFields"
                />
              </template>
              <template #default="{ row }">{{
                getSelectLabel(row.RESOURCEFIELD_ROWFIELD, funcStore.attachFields)
              }}</template>
            </je-table-column>

            <je-table-column
              v-if="!origin"
              field="RESOURCEFIELD_HIDELABEL"
              title="标签隐藏"
              width="100"
              align="center"
              type="switch"
            >
            </je-table-column>
            <!-- <je-table-column
            field="RESOURCEFIELD_NAME_EN"
            title="其他语种"
            min-width="140"
            :edit-render="{ autofocus: '.ant-input' }"
          >
            <template #edit="{ row }">
              <je-input v-model:value="row.RESOURCEFIELD_NAME_EN" />
            </template>
          </je-table-column> -->
          </je-table>
        </div>
      </template>
      <template #right>
        <!-- TODO: 通过recordData传值 -->
        <edit-field-config
          ref="editFieldConfig"
          v-model:record-data="selectField"
          :func-bean="recordData"
          :table-data="tableData.data"
          :origin="originType"
          @changeEditFieldConfig="changeEditFieldConfig"
        ></edit-field-config>
      </template>
    </je-panel>

    <div v-if="modalOption.modalFlag">
      <component
        :is="modalOption.activeModal"
        :visble="modalOption.modalFlag"
        :record-data="modalOption.recordData"
        @changeModal="changeModal"
      ></component>
    </div>
  </div>
</template>

<script>
  import {
    ref,
    reactive,
    toRefs,
    defineComponent,
    onMounted,
    defineAsyncComponent,
    onBeforeMount,
    h,
  } from 'vue';
  import {
    Dropdown,
    Grid,
    Modal,
    Panel,
    Input,
    Checkbox,
    Button,
    Select,
    Data,
    Tooltip,
    Menu,
  } from '@jecloud/ui';

  import { FORM_FIELD_CONFIG_COMPONENTS } from '@/helper/form-field-config-components';

  import { formatHightText } from '@/helper/common.js';

  import VueEvent from '@/helper/event';

  import {
    GetPluginItemConfig as GetFormFieldConfigData,
    DoFormSync,
    DoFormRemove,
    DoFormUpdateList,
    DoFormSave,
  } from '@/api/index';

  import { listenerEditorModal } from '@/helper/index.js';
  import {
    getDDItemInfo,
    isNotEmpty,
    loadDDItemByCodes,
    getAxiosBaseURL,
    getDDItemList,
  } from '@jecloud/utils';
  import { useGlobalStore } from '@common/store/global-store';
  import { useFormFields } from './hooks/use-form-fields';
  import { isArray } from '@jecloud/utils';
  export default defineComponent({
    name: 'FormFieldConfig',
    components: {
      EditFieldConfig: defineAsyncComponent({
        delay: 1000 /* 在显示加载组件之前提早毫秒 */,
        loader: () => import('./components/edit-field-config.vue'),
      }),
      JeButton: Button,
      JeInput: Input,
      JeCheckbox: Checkbox,
      JeInputSearch: Input.Search,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeTable: Grid,
      JeTableColumn: Grid.Column,
      JeModal: Modal,
      JeMenu: Menu,
      JeMenuItem: Menu.Item,
      JeDropdown: Dropdown,
      JeTooltip: Tooltip,
      JePanel: Panel,
      ...FORM_FIELD_CONFIG_COMPONENTS,
    },
    props: {
      recordData: {
        type: Object,
        default: () => {},
      },
      origin: {
        type: String,
      },
    },
    emits: ['passActionValue'],
    setup(props) {
      const { updateFuncStore, funcStore } = useFormFields();
      const state = reactive({
        tableData: Data.Store.useGridStore({
          data: [],
        }),
        searchValue: '',
        collapsed: true,
        filedsArr: [],
        editFieldConfig: ref(),
        selectTableData: [],
        loading: true,
        xTable: ref(),
        funcId: props.recordData.JE_CORE_FUNCINFO_ID,
        selectField: {},
        formPanel: ref(),
        formFieldOptions: {
          right: {
            size: 550,
            split: true,
            collapsible: true,
            collapsed: true,
            minSize: 550,
          },
        },
        formatHightText,
        name: 'formFieldConfig', // 别删，离开当前组件要用
        originType: props.origin,
        getScopedList: [],
      });

      const modalOption = reactive({
        modalFlag: false, // 默认modal都是隐藏的false
        activeModal: '', // 默认没有激活的弹窗类型
      });
      const menuActive = reactive({ show: '', recordData: props.recordData });

      //弹出关闭回调
      const btnClick = (obj) => {
        if (obj.type == 'close') {
          menuActive.show = '';
        }
      };
      //弹出代码编辑器
      const handleJs = (row) => {
        if (row) {
          listenerEditorModal({
            funcId: props.recordData.id,
            funcCode: props.recordData.code,
            funcName: props.recordData.text,
            onId: row.JE_CORE_RESOURCEFIELD_ID,
            eventType: 'field',
            fieldType: row.RESOURCEFIELD_XTYPE,
            title: '字段事件',
            callback: (obj) => {
              row.RESOURCEFIELD_JSLISTENER = obj.data;
            },
          });
        } else {
          listenerEditorModal({
            funcId: props.recordData.id,
            funcCode: props.recordData.code,
            funcName: props.recordData.text,
            eventType: 'form',
            title: '表单JS事件',
            callback: (obj) => {
              funcStore.funcBean.FUNCINFO_FORMJSLISTENER = obj.data;
            },
          });
        }
      };

      const methods = {
        // 移动端预览
        appPreview() {
          const { token } = useGlobalStore();
          const pathUrl = `${getAxiosBaseURL()}/app/micro/func/#/pages/func/form/${
            props.recordData.code
          }?authorization=${token}`;
          Modal.window({
            title: '移动端预览效果',
            maximizable: false,
            icon: 'fal fa-mobile',
            width: '476px',
            status: 'info',
            height: 'auto',
            class: 'preview-form-container',
            content() {
              return h(
                'div',
                {
                  style: {
                    overflow: 'hidden',
                    padding: '20px 40px',
                    background: '#f2f2f2',
                  },
                },
                h(
                  'div',
                  {
                    style: {
                      width: '375px',
                      height: '667px',
                      padding: '20px',
                      background: '#fff',
                      borderRadius: '30px',
                      margin: '0 auto',
                    },
                  },
                  h('iframe', {
                    src: pathUrl,
                    style: {
                      width: '100%',
                      border: '1px solid #d9d9d9',
                      height: '100%',
                      borderRadius: '10px',
                    },
                    frameborder: '0',
                    scrolling: 'no',
                    class: 'iframe-container',
                  }),
                ),
              );
            },
          });
        },
        changeJsListener(data) {
          const parseData = data ? JSON.parse(data) : [];
          let eventType = false;
          if (isArray(parseData)) {
            parseData.forEach((item) => {
              if (item.fire == '1') {
                eventType = true;
              }
            });
          }
          return eventType;
        },
        // 拖拽排序
        formFieldItemDrop() {
          state.tableData.data.forEach((item, index) => {
            item.SY_ORDERINDEX = index + 1;
          });
        },
        handleSort() {
          const showTableData = state.tableData.data.filter(
            (item) => !item.RESOURCEFIELD_HIDDEN == '0',
          );
          let showStartIndex = 1;
          let hideStartIndex = showTableData.length + 1;
          state.tableData.data.forEach((item) => {
            if (item.RESOURCEFIELD_HIDDEN == '1') {
              item.SY_ORDERINDEX = hideStartIndex++;
            } else {
              item.SY_ORDERINDEX = showStartIndex++;
            }
          });
        },
        showModal(obj) {
          modalOption.modalFlag = true;
          modalOption.activeModal = obj.type;
          modalOption.recordData = obj.data;
        },

        changeModal(value) {
          modalOption.modalFlag = value;
          methods.getData();
        },

        showEditFieldConfig(row, pos) {
          if (row.JE_CORE_RESOURCEFIELD_ID === state.selectField.JE_CORE_RESOURCEFIELD_ID) {
            state.formFieldOptions[pos].collapsed = !state.formFieldOptions[pos].collapsed;
          } else {
            state.formFieldOptions[pos].collapsed = false;
          }
          row.FUNCINFO_FUNCCODE = props.FUNCINFO_FUNCCODE;
          state.selectField = row;
        },
        onClickRow({ row }) {
          methods.showEditFieldConfig2(row, 'right');
        },
        showEditFieldConfig2(row, pos) {
          if (state.formFieldOptions[pos].collapsed) {
            return false;
          }
          state.selectField = row;
        },
        changeEditFieldConfig() {
          state.formFieldOptions['right'].collapsed = true;
        },

        // 选择表格
        selectionChange(obj) {
          state.selectTableData = obj.records;
        },

        handleChangeMenuItem(e) {
          const params = {
            tableCode: 'JE_CORE_RESOURCEFIELD',
            RESOURCEFIELD_FUNCINFO_ID: state.funcId,
            RESOURCEFIELD_XTYPE: e.key,
            RESOURCEFIELD_NAME: e.item.text,
            RESOURCEFIELD_OTHERCONFIG: e.item.text === '字段域' ? '{fieldArea:"1"}' : '',
          };

          DoFormSave(params)
            .then((res) => {
              console.log('res', res);
              state.tableData.insert(res.data);
              methods.getData();
              Modal.message(res.message, 'success');

              VueEvent.emit('refreshFormDesign');
            })
            .catch((err) => {
              console.log('error', err);
              Modal.alert(err.message, 'error');
            });
        },

        getSelectLabel(value, list, valueProp = 'value', labelField = 'label') {
          const item = list.find((item) => item[valueProp] === value);
          return item ? item[labelField] : null;
        },
        getColor(dictionary, code) {
          const item = getDDItemInfo(dictionary, code);
          if (isNotEmpty(item)) {
            return item.textColor;
          }
          return '';
        },
        getSelectCodeToLabel(dictionary, code) {
          const item = getDDItemInfo(dictionary, code);
          if (isNotEmpty(item)) {
            return item.text;
          }
          return '';
        },
        // 获取 table 数据
        getData(type) {
          state.loading = true;
          const params = {
            tableCode: 'JE_CORE_RESOURCEFIELD',
            baseSql: ` and RESOURCEFIELD_FUNCINFO_ID = '${state.funcId}'`,
            j_query: JSON.stringify({
              custom: [
                { code: 'RESOURCEFIELD_FUNCINFO_ID', value: state.funcId, type: '=', cn: 'and' },
                {
                  type: 'and',
                  value: [
                    { code: 'RESOURCEFIELD_CODE', value: state.searchValue, type: 'like' },
                    {
                      code: 'RESOURCEFIELD_NAME',
                      value: state.searchValue,
                      type: 'like',
                      cn: 'or',
                    },
                  ],
                },
              ],
              order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
            }),
            funcId: state.funcId,
          };

          GetFormFieldConfigData(params)
            .then((res) => {
              const data = res.rows;
              state.filedsArr = ['RESOURCEFIELD_UNITLISTTPL', 'RESOURCEFIELD_DESCRIPTION'];
              if (res.rows && res.rows.length) {
                Object.keys(res.rows[0]).forEach((key) => {
                  state.filedsArr.push(key);
                });
              }
              const attachArr = [];
              const fieldsetArr = [];
              data.forEach((item) => {
                // 这边要处理一下依附的数据

                const fieldOption = {
                  label: item.RESOURCEFIELD_NAME,
                  value: item.RESOURCEFIELD_CODE,
                };
                !type && item.RESOURCEFIELD_XTYPE != 'fieldset' && attachArr.push(fieldOption);
                item.RESOURCEFIELD_FIELDCOLOR = item.RESOURCEFIELD_FIELDCOLOR || '';
                // 标签颜色
                item.RESOURCEFIELD_LABELCOLOR = item.RESOURCEFIELD_LABELCOLOR || '';
                // 快查带值
                item.RESOURCECOLUMN_CHECKBANDVALUE = item.RESOURCECOLUMN_CHECKBANDVALUE || false;
                // 依附字段
                item.RESOURCEFIELD_ROWFIELD = item.RESOURCEFIELD_ROWFIELD || '';
                if (item.RESOURCEFIELD_XTYPE == 'fieldset' && !type) {
                  fieldsetArr.push(fieldOption);
                }
              });
              state.tableData.fields = state.filedsArr;

              setTimeout(() => {
                !type && updateFuncStore({ fieldsetArr, attachArr });
                // 保存完之后呢，右侧面板不要隐藏，但是需要重新打开一下，这里先获取state.tableOptions['right'].collapsed
                // 目前的实现逻辑就是if collapsed = false,那state.selectField必定有值，在此点击一下
                if (!state.formFieldOptions['right'].collapsed && state.selectField) {
                  const { JE_CORE_RESOURCEFIELD_ID } = state.selectField;
                  const arr = data.filter(
                    (item_) => item_.JE_CORE_RESOURCEFIELD_ID == JE_CORE_RESOURCEFIELD_ID,
                  );
                  state.selectField = arr && arr.length ? arr[0] : {};
                  methods.showEditFieldConfig2(state.selectField, 'right');
                }
                state.tableData.loadData(data);
                state.loading = false;
              }, 0);
            })
            .catch((err) => {
              console.log('error', err);
              Modal.alert(err.message, 'error');
            });
        },

        // 与列表同步
        handleSync() {
          Modal.confirm(
            '根据编码同步对应列表字段的“名称”、“隐藏”、“序号(排序)”数据，确定同步吗？',
            () => {
              methods.doFormSync();
            },
          );
        },

        doFormSync() {
          const params = {
            tableCode: 'JE_CORE_RESOURCEFIELD',
            RESOURCEFIELD_FUNCINFO_ID: state.funcId,
          };

          DoFormSync(params)
            .then((res) => {
              VueEvent.emit('refreshFormDesign');
              Modal.message(res.message, 'success');
              methods.getData();
            })
            .catch((err) => {
              console.log('error', err);
              Modal.alert(err.message, 'error');
            });
        },

        // 保存
        handleSave() {
          methods.formDataSave();
        },
        async formDataSave() {
          const updateRecords = state.tableData.getChanges();
          if (updateRecords.length === 0) {
            Modal.message('无数据操作!', 'info');
            return false;
          }
          const changeData = [];
          const data = [];
          updateRecords.forEach((item) => {
            data.push(item._record);
            const changeItem = {
              JE_CORE_RESOURCEFIELD_ID: item._record.JE_CORE_RESOURCEFIELD_ID,
            };
            Object.keys(item).forEach((key) => {
              if (key != '_record') {
                changeItem[key] = item[key].newValue || '';
              }
            });
            changeData.push(changeItem);
          });
          const params = {
            tableCode: 'JE_CORE_RESOURCEFIELD',
            funcId: state.funcId,
            strData: JSON.stringify(changeData),
          };
          let result = await DoFormUpdateList(params).then((res) => {
            Modal.message(res.message, 'success');
            data.forEach((item) => {
              state.tableData.commitRecord(item);
            });
            VueEvent.emit('refreshFormDesign');
            methods.getData();
            return true;
          });

          return result;
        },
        handleDelete() {
          if (state.selectTableData.length === 0) {
            Modal.alert('请选择要删除的数据！', 'warning');
            return false;
          }

          Modal.confirm('确定删除选中的数据吗？', () => {
            methods.doDelete();
          });
        },

        // 删除
        doDelete() {
          const ids = state.selectTableData.map((item) => item.JE_CORE_RESOURCEFIELD_ID).join(',');

          const params = {
            tableCode: 'JE_CORE_RESOURCEFIELD',
            ids,
          };

          DoFormRemove(params).then((res) => {
            state.selectTableData.forEach((item) => {
              state.tableData.remove(item);
            });

            state.selectTableData = [];
            Modal.message(res.message, 'success');
            methods.getData();

            VueEvent.emit('refreshFormDesign');
          });
        },
        // 根据条件改变某一行的某一项
        cellClassName({ row, column }) {
          // start 这边如果是系统字段的话，序号和编码要变蓝色
          if (
            (column.property === 'RESOURCEFIELD_NAME' ||
              column.property === 'RESOURCEFIELD_CODE') &&
            row.RESOURCEFIELD_CODE.substring(0, 3) == 'SY_'
          ) {
            return 'row-sys-cls';
          }
          // end
          return '';
        },
        // 根据条件改变单元格的样式
        rowClassName({ row }) {
          if (row.RESOURCEFIELD_CODE.substring(0, 3) == 'SY_') {
            return 'row-sys-cls';
          }
        },
      };
      onBeforeMount(() => {
        // 获取字典数据
        loadDDItemByCodes([
          'JE_FUNC_FIELD_ALIGN',
          'JE_FUNC_FIELD_XTYPE',
          'JE_META_USE_SCOPE',
          'JE_FUNC_FIELD_APP_ALIGN',
        ]);
        state.getScopedList = getDDItemList('JE_META_USE_SCOPE') || [
          { code: 'ALL', text: '全部', textColor: '', icon: 'fal fa-phone-laptop' },
          { code: 'APP', text: '移动端', textColor: '#02A863', icon: 'fal fa-mobile-phone' },
          { code: 'PC', text: '电脑端', textColor: '#3265F5', icon: 'fal fa-laptop' },
        ];
      });
      onMounted(() => {
        methods.getData();

        VueEvent.off('refreshFormFieldConfig');
        VueEvent.on('refreshFormFieldConfig', () => {
          methods.getData();
        });
      });

      return {
        funcStore,
        ...toRefs(state),
        ...methods,
        modalOption,
        handleJs,
        menuActive,
        btnClick,
      };
    },
  });
</script>
<style lang="less">
  .preview-form-container {
    .je-modal--body {
      padding: 0 !important;
    }
  }
  .form-field-config {
    .iframe-container {
      overflow: scroll;
      ::-webkit-scrollbar {
        width: 0 !important;
      }
    }
    .searchWrap {
      margin: 0 0 0 auto;
      .ant-input-search {
        border-bottom-right-radius: 0;
        border-top-right-radius: 0;
      }
      .ant-input-affix-wrapper-focused {
        box-shadow: none !important;
      }
      .ant-btn {
        width: 60px;
        background: #3265f5;
      }
    }
    .tableWrap {
      .table {
        .row-sys-cls td:nth-of-type(1),
        .row-sys-cls td:nth-of-type(2) {
          color: rgba(0, 0, 0, 0.85) !important;
        }
        .row-sys-cls {
          color: #3265f5;
        }
      }
    }
  }
</style>
<style lang="less" scoped>
  .form-field-config {
    // position: relative;
    width: 100%;
    height: 100%;
    .top {
      display: flex;
      align-items: center;
      height: 40px;
      padding: 0 20px 0 4px;
      background: #f7f9fc;
      > .ant-btn {
        padding: 4px 12px !important;
        &:hover {
          color: #3f3f3f !important;
          background: #d9d9d9 !important;
        }
      }
    }
    .tableWrap {
      // position: absolute;
      // top: 40px;
      // bottom: 0;
      // width: 100%;
      // overflow: auto;
      .table {
        .iconWrap {
          cursor: pointer;
        }
        .eventWrap {
          cursor: pointer;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
</style>
